package permission

import (
	"gorm.io/gorm"
)

// Repository 权限数据访问层接口
type Repository interface {
	Create(permission *Permission) error
	GetByID(id uint) (*Permission, error)
	GetByName(name string) (*Permission, error)
	GetByNameIncludeDeleted(name string) (*Permission, error)
	RestorePermission(id uint, req *CreateRequest) (*Permission, error)
	Update(permission *Permission) error
	Delete(id uint) error
	List(req *QueryRequest) ([]*Permission, int64, error)
	GetTree() ([]*Permission, error)
	GetAllPermissions() ([]*Permission, error)
	GetChildrenByParentID(parentID uint) ([]*Permission, error)
}

// repository 权限数据访问层实现
type repository struct {
	db *gorm.DB
}

// NewRepository 创建权限数据访问层
func NewRepository(db *gorm.DB) Repository {
	return &repository{
		db: db,
	}
}

// Create 创建权限
func (r *repository) Create(permission *Permission) error {
	return r.db.Create(permission).Error
}

// GetByID 根据ID获取权限
func (r *repository) GetByID(id uint) (*Permission, error) {
	var permission Permission
	err := r.db.First(&permission, id).Error
	if err != nil {
		return nil, err
	}
	return &permission, nil
}

// GetByName 根据名称获取权限
func (r *repository) GetByName(name string) (*Permission, error) {
	var permission Permission
	err := r.db.Where("name = ?", name).First(&permission).Error
	if err != nil {
		return nil, err
	}
	return &permission, nil
}

// GetByNameIncludeDeleted 根据名称获取权限（包括软删除的记录）
func (r *repository) GetByNameIncludeDeleted(name string) (*Permission, error) {
	var permission Permission
	err := r.db.Unscoped().Where("name = ?", name).First(&permission).Error
	if err != nil {
		return nil, err
	}
	return &permission, nil
}

// RestorePermission 恢复软删除的权限
func (r *repository) RestorePermission(id uint, req *CreateRequest) (*Permission, error) {
	var permission Permission

	// 先获取软删除的记录
	err := r.db.Unscoped().First(&permission, id).Error
	if err != nil {
		return nil, err
	}

	// 更新权限信息
	permission.Name = req.Name
	permission.DisplayName = req.DisplayName
	if permission.DisplayName == "" {
		permission.DisplayName = req.Name
	}
	permission.Description = req.Description
	permission.Path = req.Path
	permission.Method = req.Method
	permission.Type = req.Type
	if permission.Type == "" {
		permission.Type = "menu"
	}
	permission.Icon = req.Icon

	// 处理父权限ID
	if req.ParentID != nil {
		if *req.ParentID == 0 {
			zero := uint(0)
			permission.ParentID = &zero
			permission.Level = 1
		} else {
			permission.ParentID = req.ParentID
			// 重新计算层级
			parent, err := r.GetByID(*req.ParentID)
			if err != nil {
				return nil, err
			}
			permission.Level = parent.Level + 1
		}
	}

	if req.Sort != nil {
		permission.Sort = *req.Sort
	}
	if req.Status != nil {
		permission.Status = *req.Status
	} else {
		permission.Status = 1
	}

	// 恢复记录（清除 deleted_at）
	permission.DeletedAt = gorm.DeletedAt{Valid: false}

	// 保存更新
	err = r.db.Unscoped().Save(&permission).Error
	if err != nil {
		return nil, err
	}

	return &permission, nil
}

// Update 更新权限
func (r *repository) Update(permission *Permission) error {
	return r.db.Save(permission).Error
}

// Delete 删除权限
func (r *repository) Delete(id uint) error {
	return r.db.Delete(&Permission{}, id).Error
}

// List 获取权限列表
func (r *repository) List(req *QueryRequest) ([]*Permission, int64, error) {
	var permissions []*Permission
	var total int64

	query := r.db.Model(&Permission{})

	// 关键词搜索
	if req.Keyword != "" {
		query = query.Where("name LIKE ? OR display_name LIKE ? OR description LIKE ?",
			"%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	// 字段筛选
	if req.Name != "" {
		query = query.Where("name = ?", req.Name)
	}

	if req.DisplayName != "" {
		query = query.Where("display_name = ?", req.DisplayName)
	}

	if req.Type != "" {
		query = query.Where("type = ?", req.Type)
	}

	if req.ParentID != nil {
		query = query.Where("parent_id = ?", *req.ParentID)
	}

	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Offset(offset).Limit(req.PageSize).Order("sort ASC, id ASC").Find(&permissions).Error; err != nil {
		return nil, 0, err
	}

	return permissions, total, nil
}

// GetTree 获取权限树（返回平铺数据，由service层构建树）
func (r *repository) GetTree() ([]*Permission, error) {
	var permissions []*Permission
	err := r.db.Where("status = ?", 1).Order("sort ASC, id ASC").Find(&permissions).Error
	return permissions, err
}

// GetAllPermissions 获取所有权限（用于下拉选择等）
func (r *repository) GetAllPermissions() ([]*Permission, error) {
	var permissions []*Permission
	err := r.db.Where("status = ?", 1).Order("sort ASC, id ASC").Find(&permissions).Error
	return permissions, err
}

// GetChildrenByParentID 根据父ID获取子权限
func (r *repository) GetChildrenByParentID(parentID uint) ([]*Permission, error) {
	var permissions []*Permission
	err := r.db.Where("parent_id = ? AND status = ?", parentID, 1).Order("sort ASC, id ASC").Find(&permissions).Error
	return permissions, err
}
